package com.onec.service.netty.example;

import com.onec.service.netty.demo.NettyDisCardHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * netty  项目
 */
public class NettyEchoService {

    Logger log = LoggerFactory.getLogger(NettyEchoService.class);
    ServerBootstrap bootstrap = new ServerBootstrap();
    final static int part = 9999;

    public void runService() throws InterruptedException {
        // 创建反应器轮询组
        EventLoopGroup boosLoopGroup = new NioEventLoopGroup(1);
        // 工作线程轮询组
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();
        try {
            // 设置反应器轮询组
            bootstrap.group(boosLoopGroup, workerLoopGroup);
            // 设置nio 类型的通道
            bootstrap.channel(NioServerSocketChannel.class);
            // 设置监听端口
            bootstrap.localAddress(part);
            // 设置通道参数
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            // 装配子通道流水线
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline().addLast(new NettyDisCardHandler());
                }
            });

            // 绑定服务其 sync 同步方法阻塞 知道成功
            ChannelFuture channelFuture = bootstrap.bind().sync();
            log.info("服务启动成功，监听的端口为：{}", channelFuture.channel().localAddress());

            // 等待  通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 优雅的关闭同时释放资源
            workerLoopGroup.shutdownGracefully();
            boosLoopGroup.shutdownGracefully();
        }
    }


}
